package com.asc.ascoa;

import com.util.crypto.CryptoSystemClient;
import com.util.database.DatabaseManager;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet(name = "Register", value = "/register")
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");

        String error = null;

        String password = null;
        try {
            password = CryptoSystemClient.encry(request.getParameter("password"));
        } catch (Exception e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        }

        DatabaseManager databaseManager = null;

        try {
            databaseManager = new DatabaseManager();
        } catch (ClassNotFoundException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        } catch (SQLException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        }

        try {
            databaseManager.executeUpdate("INSERT INTO `user` VALUES (\"" + username + "\",\"" + password + "\")");
        } catch (SQLException e) {
            error += e + "\n";
            //throw new RuntimeException(e);
        }

        //response
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");

        if (error == null) out.println("<h1>SUCCESS</h1>");
        else out.println("<h1>" + error+ "</h1>");;
        out.println("</body></html>");

    }
}
